#!/bin/sh

d() {
    echo $1 > /dev/null
}

mount_fqrouter_partition() {
    for disk in $(find /dev/sd*)
    do
        d $(mount -o noatime $disk /udisk 2>&1)
        if [ -f /udisk/fqrouter/boot ] ; then
            echo "found fqrouter in $disk"
            return
        fi
        d $(umount /udisk 2>&1)
    done
}

switch_to_rootfs() {
    if [ -n "$INITRAMFS" ]; then
        load_modules /etc/modules /etc/modules.d/*
        sleep 3 # wait for /dev/sd*
        mkdir /udisk
        mount_fqrouter_partition
        if [ ! -f /udisk/fqrouter/boot ] ; then
            echo 'skip usb boot due to the boot file not found'
            sleep 1
            export FQROUTER_BOOT_ERROR="skip usb boot due to the boot file not found"
            exec /sbin/init
        fi
        . /udisk/fqrouter/boot
        echo "fqrouter version: $FQROUTER_VERSION"
        if [ ! -f /udisk/fqrouter/$FQROUTER_VERSION.rootfs ] ; then
            echo 'skip usb boot due to rootfs not found'
            sleep 1
            export FQROUTER_BOOT_ERROR="skip usb boot due to rootfs not found"
            exec /sbin/init
        fi
        losetup /dev/loop1 /udisk/fqrouter/$FQROUTER_VERSION.rootfs
        if [ $? -ne 0 ] ; then
            echo 'skip usb boot due to loopback mount failed'
            sleep 1
            export FQROUTER_BOOT_ERROR="skip usb boot due to loopback mount failed"
            exec /sbin/init
        fi
        mkdir /mnt
        mount -o noatime -t ext4 /dev/loop1 /mnt
        mkdir /mnt/udisk
        mount -o noatime,move /udisk /mnt/udisk
        mkdir /mnt/udisk/fqrouter/config
        if [ ! -d /mnt/etc/config.orig ] ; then
            mv /mnt/etc/config /mnt/etc/config.orig
            mkdir /mnt/etc/config
        fi
        mount -t overlayfs -o lowerdir=/mnt/etc/config.orig,upperdir=/mnt/udisk/fqrouter/config overlayfs /mnt/etc/config
        mount -o noatime,move /proc /mnt/proc
        mount -o noatime,move /dev /mnt/dev
        mount -o noatime,move /dev/pts /mnt/dev/pts
        mount -o noatime,move /tmp /mnt/tmp
        mount -o noatime,move /sys /mnt/sys
        mount -o noatime none /tmp -t tmpfs
        echo 'about to switch root'
        exec switch_root -c /dev/console /mnt /sbin/init
    fi
}

boot_hook_add initramfs switch_to_rootfs